package user

import (
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Core"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Rt"
)

// get user list
func GetList() (users []map[string]string) {
	sql := Core.Sql("fuxiaohei_users").Order("id ASC").Select()
	users = Core.Db.All(sql)
	return
}

// get one user by id
func GetOneById(id string) (user map[string]string) {
	sql := Core.Sql("fuxiaohei_users").Where("id = ?").Select()
	user = Core.Db.One(sql, id)
	return
}

// validate user data for updating
func validateUserData(data map[string]string) string {
	if Rt.Validator.IsShorter(data["real_name"], 2) {
		return "昵称必须大于1个字"
	}
	if Rt.Validator.IsShorter(data["user"], 4) {
		return "用户名必须大于3个字符"
	}
	if !Rt.Validator.IsEmail(data["email"]) {
		return "邮件格式错误"
	}
	return ""
}

// update user data
func UpdateUser(id string, data map[string]string) {
	// if admin, do not update status and role_name
	if data["status"] != "" || data["role_name"] != "" {
		sql := Core.Sql("fuxiaohei_users", "user,email,url,real_name,bio,status,role_name").Where("id = ?").Update()
		Core.Db.Exec(sql, data["user"], data["email"], data["url"], data["real_name"], data["bio"], data["status"], data["role_name"], id)
		return
	}
	sql := Core.Sql("fuxiaohei_users", "user,email,url,real_name,bio").Where("id = ?").Update()
	Core.Db.Exec(sql, data["user"], data["email"], data["url"], data["real_name"], data["bio"], id)
}

// update user password
func UpdatePassword(id string, newPassword string) {
	newPassword = Rt.Crypto.Sha1Salt(newPassword, Core.Config.String("salt.password"))
	sql := Core.Sql("fuxiaohei_users", "password").Where("id = ?").Update()
	Core.Db.Exec(sql, newPassword, id)
}

// add new user
func AddUser(data map[string]string) {
	data["password"] = Rt.Crypto.Sha1Salt(data["password"], Core.Config.String("salt.password"))
	sql := Core.Sql("fuxiaohei_users", "user,password,email,url,real_name,bio,status,role_name,add_time").Insert()
	Core.Db.Exec(sql, data["user"], data["password"], data["email"], data["url"], data["real_name"], data["bio"], data["status"], data["role_name"], Rt.Time.Now())
}

// check user email existed
func checkEmailExist(email string) bool {
	sql := Core.Sql("fuxiaohei_users", "id").Where("email = ?").Select()
	user := Core.Db.One(sql, email)
	if len(user) > 0 {
		return user["id"] != ""
	}
	return false
}


